package com.example.musicplayer.musicTools;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;

import com.example.musicplayer.MusicPlayerApplication;
import com.example.musicplayer.commonUtils.DrawUtil;
import com.example.musicplayer.musicClass.MusicInfo;
import com.example.musicplayer.musicClass.MusicMenu;
import com.example.musicplayer.provider.DBConstants;
import com.example.musicplayer.user.User;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LocalMusic {
    private static final String URI_MUSIC = "content://com.example.musicplayer.provider.MusicContentProvider/";
    private static final ContentResolver RESOLVER;
    private static final Uri URI_MUSIC_DETAIL;

    static {
        URI_MUSIC_DETAIL = Uri.parse(URI_MUSIC + DBConstants.MusicDetail.TABLE_NAME);
        RESOLVER = MusicPlayerApplication.getInstance().getContentResolver();
    }

    //获取本地所有歌曲
    public static List<MusicInfo> getLocalMusic() {
        List<MusicInfo> musicList = new ArrayList<MusicInfo>();
        //要读取的列名
        String[] projection = new String[]{MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ALBUM_ID, MediaStore.Audio.Media.SIZE
                , MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ALBUM
                , MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.DATA};
        Cursor cursor = RESOLVER.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection
                , null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
                int albumId = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                int size = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
                String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                MusicFormat musicFormat = new MusicFormat(path);
                musicList.add(new MusicInfo(id, albumId, size, title, album, artist, path, musicFormat));
            }
            cursor.close();
        }
        return musicList;
    }

    //获取本地所有歌单信息
    public static List<MusicMenu> getLocalMusicMenu() {
        Uri uri = Uri.parse(URI_MUSIC + DBConstants.MusicMenuManage.TABLE_NAME + User.getInstance().getUserId());
        List<MusicMenu> musicMenuList = new ArrayList<MusicMenu>();
        Cursor cursor = RESOLVER.query(uri, new String[]{DBConstants.MusicMenuManage.NAME,
                DBConstants.MusicMenuManage.MENU_ORDER, DBConstants.MusicMenuManage.MENU_TABLE_NAME,
                DBConstants.MusicMenuManage.MATCH_CODE, DBConstants.MusicMenuManage.LISTEN_COUNTS
                , DBConstants.MusicMenuManage.BITMAP}, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String name = cursor.getString(cursor.getColumnIndex(DBConstants.MusicMenuManage.NAME));
                int order = cursor.getInt(cursor.getColumnIndex(DBConstants.MusicMenuManage.MENU_ORDER));
                String tableName = cursor.getString(cursor.getColumnIndex(DBConstants.MusicMenuManage.MENU_TABLE_NAME));
                int matchCode = cursor.getInt(cursor.getColumnIndex(DBConstants.MusicMenuManage.MATCH_CODE));
                int listenCounts = cursor.getInt(cursor.getColumnIndex(DBConstants.MusicMenuManage.LISTEN_COUNTS));
                int bitmap = cursor.getInt(cursor.getColumnIndex(DBConstants.MusicMenuManage.BITMAP));
                if (UserTableManager.addMusicMenuDetailData(name, tableName, matchCode)) {
                    musicMenuList.add(new MusicMenu(name, order, listenCounts, bitmap));
                }
            }
            cursor.close();
        }
        return musicMenuList;
    }

    //get music menu detail id info
    public static List<Integer> getMusicMenuDetailId(String tableName) {
        Uri uri = Uri.parse(URI_MUSIC + tableName);
        List<Integer> musicId = new ArrayList<Integer>();
        Cursor cursor = RESOLVER.query(uri, new String[]{DBConstants.MusicMenuDetail.ID},
                null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex(DBConstants.MusicMenuDetail.ID));
                musicId.add(id);
            }
            cursor.close();
        }
        return musicId;
    }

    //get music menu detail order info
    public static List<Integer> getMusicMenuDetailOrder(String tableName) {
        Uri uri = Uri.parse(URI_MUSIC + tableName);
        List<Integer> musicOrder = new ArrayList<Integer>();
        Cursor cursor = RESOLVER.query(uri, new String[]{DBConstants.MusicMenuDetail.MUSIC_ORDER},
                null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                int order = cursor.getInt(cursor.getColumnIndex(DBConstants.MusicMenuDetail.MUSIC_ORDER));
                musicOrder.add(order);
            }
            cursor.close();
        }
        return musicOrder;
    }

    //查询歌单简介
    public static String getMusicMenuIntroduction(String musicMenuName) {
        Cursor cursor;
        Uri uri = Uri.parse(URI_MUSIC + UserTableManager.getMusicMenuManageName());
        synchronized (RESOLVER) {
            cursor = RESOLVER.query(uri, new String[]{DBConstants.MusicMenuManage.INTRODUCTION},
                    DBConstants.MusicMenuManage.NAME + "=?", new String[]{musicMenuName}, null);
        }
        if (cursor != null) {
            if (cursor.moveToNext()) {
                return cursor.getString(cursor.getColumnIndex(DBConstants.MusicMenuManage.INTRODUCTION));
            }
            cursor.close();
        }
        return "";
    }

    //查询歌单的歌曲排序类型
    public static String getMusicSortType(final String musicMenuName) {
        Uri uri = Uri.parse(URI_MUSIC + DBConstants.MusicMenuManage.TABLE_NAME + User.getInstance().getUserId());
        Cursor cursor;
        synchronized (RESOLVER) {
            cursor = RESOLVER.query(uri, new String[]{DBConstants.MusicMenuManage.MUSIC_SORT_TYPE},
                    DBConstants.MusicMenuManage.NAME + "=?", new String[]{musicMenuName}, null);
        }
        String musicSortType = null;
        if (cursor != null) {
            if (cursor.moveToNext()) {
                musicSortType = cursor.getString(cursor.getColumnIndex(DBConstants.MusicMenuManage.MUSIC_SORT_TYPE));
            }
            cursor.close();
        }
        return musicSortType;
    }

    public static boolean getIfNeedUpdateMusicMenuDetail(String musicMenuName) {
        Cursor cursor;
        Uri uri = Uri.parse(URI_MUSIC + UserTableManager.getMusicMenuManageName());
        synchronized (RESOLVER) {
            cursor = RESOLVER.query(uri, new String[]{DBConstants.MusicMenuManage.DATA_1},
                    DBConstants.MusicMenuManage.NAME + "=?", new String[]{musicMenuName}, null);
        }
        String data_1 = "";
        if (cursor != null) {
            if (cursor.moveToNext()) {
                data_1 = cursor.getString(cursor.getColumnIndex(DBConstants.MusicMenuManage.DATA_1));
            }
            cursor.close();
        }
        return data_1.length() > 0;
    }

    public static Map<Integer, Integer> getMusicDetailFavorite() {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        Uri uri = Uri.parse(URI_MUSIC + UserTableManager.getMusicDetailUserName());
        Cursor cursor;
        synchronized (RESOLVER) {
            cursor = RESOLVER.query(uri, new String[]{DBConstants.MusicDetailUser.ID, DBConstants.MusicDetailUser.FAVORITE}
                    , null, null, null);
        }
        if (cursor != null) {
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex(DBConstants.MusicDetailUser.ID));
                int favorite = cursor.getInt(cursor.getColumnIndex(DBConstants.MusicDetailUser.FAVORITE));
                map.put(id, favorite);
            }
            cursor.close();
        }
        return map;
    }

    public static Map<Integer, Integer> getMusicDetailListenCounts() {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        Uri uri = Uri.parse(URI_MUSIC + UserTableManager.getMusicDetailUserName());
        Cursor cursor;
        synchronized (RESOLVER) {
            cursor = RESOLVER.query(uri, new String[]{DBConstants.MusicDetailUser.ID, DBConstants.MusicDetailUser.LISTEN_COUNTS}
                    , null, null, null);
        }
        if (cursor != null) {
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex(DBConstants.MusicDetailUser.ID));
                int listenCounts = cursor.getInt(cursor.getColumnIndex(DBConstants.MusicDetailUser.LISTEN_COUNTS));
                map.put(id, listenCounts);
            }
            cursor.close();
        }
        return map;
    }

    //更新给定歌曲的播放次数
    public static void updateMusicListenCounts(final int musicId, final int listenCounts) {
        ContentValues values = new ContentValues();
        Uri uri = Uri.parse(URI_MUSIC + UserTableManager.getMusicDetailUserName());
        values.put(DBConstants.MusicDetailUser.LISTEN_COUNTS, listenCounts);
        synchronized (RESOLVER) {
            RESOLVER.update(uri, values, DBConstants.MusicDetailUser.ID + "=?", new String[]{String.valueOf(musicId)});
        }
    }

    //在music_favorite数据表中更新数据
    public static void updateMusicFavorite(MusicInfo newMusicInfo) {
        if (newMusicInfo != null) {
            final MusicInfo musicInfo = newMusicInfo;
            new Thread() {
                @Override
                public void run() {
                    //记录操作结果
                    int result = 0;
                    ContentValues values = new ContentValues();
                    values.put(DBConstants.MusicDetailUser.FAVORITE, musicInfo.getFavorite());
                    int id = musicInfo.getId();
                    synchronized (RESOLVER) {
                        Uri uri = Uri.parse(URI_MUSIC + UserTableManager.getMusicDetailUserName());
                        result = RESOLVER.update(uri, values, DBConstants.MusicDetailUser.ID + "=?"
                                , new String[]{String.valueOf(id)});
                    }
                    //更新数据库失败，重置favorite
                    if (result == 0) {
                        musicInfo.setFavorite(1 - musicInfo.getFavorite());
                    }
                }
            }.start();
        }
    }

    //在歌单信息表中更新歌单的顺序
    public static void updateMusicMenuOrder(final List<MusicMenu> musicMenus) {
        new Thread() {
            @Override
            public void run() {
                ContentValues values;
                synchronized (RESOLVER) {
                    Uri uri = Uri.parse(URI_MUSIC + UserTableManager.getMusicMenuManageName());
                    for (int i = 0; i < musicMenus.size(); i++) {
                        String name = musicMenus.get(i).getName();
                        int order = musicMenus.get(i).getOrder();
                        values = new ContentValues();
                        values.put(DBConstants.MusicMenuManage.MENU_ORDER, order);
                        RESOLVER.update(uri, values, DBConstants.MusicMenuManage.NAME + "=?", new String[]{name});
                    }
                }
            }
        }.start();
    }

    //更新歌单名字
    public static void updateMusicMenuName(final String oldMusicMenuName, final String newMusicMenuName) {
        new Thread() {
            @Override
            public void run() {
                ContentValues values;
                synchronized (RESOLVER) {
                    values = new ContentValues();
                    values.put(DBConstants.MusicMenuManage.NAME, newMusicMenuName);
                    Uri uri = Uri.parse(URI_MUSIC + UserTableManager.getMusicMenuManageName());
                    RESOLVER.update(uri, values, DBConstants.MusicMenuManage.NAME + "=?", new String[]{oldMusicMenuName});
                }
            }
        }.start();
    }

    //更新歌单的点播次数
    public static void updateMusicMenuListenCounts(final String musicMenuName, final int listenCounts) {
        ContentValues values = new ContentValues();
        values.put(DBConstants.MusicMenuManage.LISTEN_COUNTS, listenCounts);
        synchronized (RESOLVER) {
            Uri uri = Uri.parse(URI_MUSIC + UserTableManager.getMusicMenuManageName());
            RESOLVER.update(uri, values, DBConstants.MusicMenuManage.NAME + "=?", new String[]{musicMenuName});
        }
    }

    //更新歌单封面
    public static void updateMusicMenuBitmap(final String musicMenuName, final int bitmap) {
        ContentValues values = new ContentValues();
        values.put(DBConstants.MusicMenuManage.BITMAP, bitmap);
        synchronized (RESOLVER) {
            Uri uri = Uri.parse(URI_MUSIC + UserTableManager.getMusicMenuManageName());
            RESOLVER.update(uri, values, DBConstants.MusicMenuManage.NAME + "=?", new String[]{musicMenuName});
        }
    }

    //更新歌单简介
    public static void updateMusicMenuIntroduction(final String musicMenuName, final String introduction) {
        ContentValues values = new ContentValues();
        values.put(DBConstants.MusicMenuManage.INTRODUCTION, introduction);
        synchronized (RESOLVER) {
            Uri uri = Uri.parse(URI_MUSIC + UserTableManager.getMusicMenuManageName());
            RESOLVER.update(uri, values, DBConstants.MusicMenuManage.NAME + "=?", new String[]{musicMenuName});
        }
    }

    //更新歌单的歌曲排序类型
    public static void updateMusicMenuMusicSortType(final String musicMenuName, final String musicSortType) {
        ContentValues values = new ContentValues();
        values.put(DBConstants.MusicMenuManage.MUSIC_SORT_TYPE, musicSortType);
        synchronized (RESOLVER) {
            Uri uri = Uri.parse(URI_MUSIC + UserTableManager.getMusicMenuManageName());
            RESOLVER.update(uri, values, DBConstants.MusicMenuManage.NAME + "=?", new String[]{musicMenuName});
        }
    }

    public static void updateIfNeedUpdateMusicMenuDetail(final String musicMenuName, final boolean needUpdate) {
        ContentValues values = new ContentValues();
        values.put(DBConstants.MusicMenuManage.DATA_1, needUpdate ? "1" : "");
        synchronized (RESOLVER) {
            Uri uri = Uri.parse(URI_MUSIC + UserTableManager.getMusicMenuManageName());
            RESOLVER.update(uri, values, DBConstants.MusicMenuManage.NAME + "=?", new String[]{musicMenuName});
        }
    }

    //更新指定歌单里的部分歌曲的默认排序
    public static void updateMusicMenuMusicOrder(final String tableName, final List<Integer> musicId
            , final List<Integer> musicOrder) {
        new Thread() {
            @Override
            public void run() {
                Uri uri = Uri.parse(URI_MUSIC + tableName);
                ContentValues values = new ContentValues();
                synchronized (RESOLVER) {
                    for (int i = 0; i < musicId.size(); i++) {
                        values.put(DBConstants.MusicMenuDetail.MUSIC_ORDER, musicOrder.get(i));
                        RESOLVER.update(uri, values, DBConstants.MusicMenuDetail.ID + "=?"
                                , new String[]{String.valueOf(musicId.get(i))});
                    }
                }
            }
        }.start();
    }

    //insert data into music detail table
    private static void insertMusicDetail(List<MusicInfo> list) {
        if (list == null) {
            return;
        }
        synchronized (RESOLVER) {
            for (int i = 0; i < list.size(); i++) {
                ContentValues values = new ContentValues();
                MusicInfo musicInfo = list.get(i);
                values.put(DBConstants.MusicDetail.ID, musicInfo.getId());
                values.put(DBConstants.MusicDetail.ALBUM_ID, musicInfo.getAlbumId());
                values.put(DBConstants.MusicDetail.SIZE, musicInfo.getSize());
                values.put(DBConstants.MusicDetail.TITLE, musicInfo.getTitle());
                values.put(DBConstants.MusicDetail.ALBUM, musicInfo.getAlbum());
                values.put(DBConstants.MusicDetail.ARTIST, musicInfo.getArtist());
                values.put(DBConstants.MusicDetail.PATH, musicInfo.getPath());
                values.put(DBConstants.MusicDetail.LYRIC_PATH, musicInfo.getLyricPath());
                values.put(DBConstants.MusicDetail.DATA_1, "");
                values.put(DBConstants.MusicDetail.DATA_2, "");
                RESOLVER.insert(URI_MUSIC_DETAIL, values);
            }
        }
    }

    private static void insertMusicDetailUser(List<MusicInfo> list) {
        if (list == null) {
            return;
        }
        synchronized (RESOLVER) {
            for (int i = 0; i < list.size(); i++) {
                ContentValues values = new ContentValues();
                MusicInfo musicInfo = list.get(i);
                values.put(DBConstants.MusicDetailUser.ID, musicInfo.getId());
                values.put(DBConstants.MusicDetailUser.FAVORITE, 0);
                values.put(DBConstants.MusicDetailUser.LISTEN_COUNTS, 0);
                values.put(DBConstants.MusicDetailUser.AUTHORITY, 1);
                values.put(DBConstants.MusicDetailUser.DATA_1, "");
                values.put(DBConstants.MusicDetailUser.DATA_2, "");
                RESOLVER.insert(Uri.parse(URI_MUSIC + UserTableManager.getMusicDetailUserName()), values);
            }
        }
    }

    //向歌单信息表插入新建歌单的信息
    public static void insertMusicMenuManage(final String musicMenuName) {
        final String tableName = UserTableManager.getTableNameByMenuName(musicMenuName);
        final int matchCode = UserTableManager.getMatchCodeByMenuName(musicMenuName);
        new Thread() {
            @Override
            public void run() {
                ContentValues values = new ContentValues();
                int order = 0;
                values.put(DBConstants.MusicMenuManage.NAME, musicMenuName);
                values.put(DBConstants.MusicMenuManage.MENU_ORDER, order);
                values.put(DBConstants.MusicMenuManage.MENU_TABLE_NAME, tableName);
                values.put(DBConstants.MusicMenuManage.MATCH_CODE, matchCode);
                values.put(DBConstants.MusicMenuManage.INTRODUCTION, "");
                values.put(DBConstants.MusicMenuManage.BITMAP, 0);
                values.put(DBConstants.MusicMenuManage.LISTEN_COUNTS, 0);
                values.put(DBConstants.MusicMenuManage.MUSIC_SORT_TYPE, MusicSortType.SORT_DEFAULT.toString());
                values.put(DBConstants.MusicMenuManage.DATA_1, "");
                values.put(DBConstants.MusicMenuManage.DATA_2, "");
                synchronized (RESOLVER) {
                    RESOLVER.insert(Uri.parse(URI_MUSIC + UserTableManager.getMusicMenuManageName()), values);
                }
            }
        }.start();
    }

    //向歌单插入新的音乐
    public static void insertMusicMenuDetail(final String tableName, final List<Integer> list
            , final List<Integer> musicOrder) {
        new Thread() {
            @Override
            public void run() {
                Uri uri = Uri.parse(URI_MUSIC + tableName);
                ContentValues values = new ContentValues();
                synchronized (RESOLVER) {
                    for (int i = 0; i < list.size(); i++) {
                        values.put(DBConstants.MusicMenuDetail.ID, list.get(i));
                        values.put(DBConstants.MusicMenuDetail.MUSIC_ORDER, musicOrder.get(i));
                        values.put(DBConstants.MusicMenuDetail.DATA_1, "");
                        values.put(DBConstants.MusicMenuDetail.DATA_2, "");
                        RESOLVER.insert(uri, values);
                    }
                }
            }
        }.start();
    }

    private static void deleteMusicDetail(final List<Integer> list) {
        if (list != null) {
            new Thread() {
                @Override
                public void run() {
                    String[] selectionArgs = new String[1];
                    synchronized (RESOLVER) {
                        for (int i = 0; i < list.size(); i++) {
                            selectionArgs[0] = String.valueOf(list.get(i));
                            RESOLVER.delete(URI_MUSIC_DETAIL, DBConstants.MusicDetail.ID + "=?", selectionArgs);
                        }
                    }
                }
            }.start();
        }
    }

    private static void deleteMusicDetailUser(final List<Integer> list) {
        if (list != null) {
            new Thread() {
                @Override
                public void run() {
                    String[] selectionArgs = new String[1];
                    Uri uri = Uri.parse(URI_MUSIC + UserTableManager.getMusicDetailUserName());
                    synchronized (RESOLVER) {
                        for (int i = 0; i < list.size(); i++) {
                            selectionArgs[0] = String.valueOf(list.get(i));
                            RESOLVER.delete(uri, DBConstants.MusicDetailUser.ID + "=?", selectionArgs);
                        }
                    }
                }
            }.start();
        }
    }

    //从歌单信息表删除歌单的信息
    public static void deleteMusicMenuManage(final String musicMenuName) {
        new Thread() {
            @Override
            public void run() {
                Uri uri = Uri.parse(URI_MUSIC + UserTableManager.getMusicMenuManageName());
                synchronized (RESOLVER) {
                    RESOLVER.delete(uri, DBConstants.MusicMenuManage.NAME + "=?", new String[]{musicMenuName});
                }
            }
        }.start();
    }

    //从歌单删除音乐
    public static void deleteMusicMenuDetail(final String tableName, final List<Integer> list) {
        new Thread() {
            @Override
            public void run() {
                Uri uri = Uri.parse(URI_MUSIC + tableName);
                String[] selectionArgs = new String[1];
                synchronized (RESOLVER) {
                    for (int i = 0; i < list.size(); i++) {
                        selectionArgs[0] = String.valueOf(list.get(i));
                        RESOLVER.delete(uri, DBConstants.MusicMenuDetail.ID + "=?", selectionArgs);
                    }
                }
            }
        }.start();
    }

    //查询music_favorite表，初始化favorite信息,若有缺失的歌曲则插入新的favorite信息
    public static void checkMusicDetail() {
        Cursor cursor;
        synchronized (RESOLVER) {
            cursor = RESOLVER.query(URI_MUSIC_DETAIL, new String[]{DBConstants.MusicDetail.ID},
                    null, null, null);
        }
        if (cursor != null) {
            //local music list
            List<MusicInfo> localMusic = MusicInfo.getLocalMusic();
            List<Integer> deleteMusic = new ArrayList<Integer>();
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex(DBConstants.MusicDetail.ID));
                MusicInfo temp = MusicInfo.getMusicInfoById(id);
                if (temp != null) {
                    localMusic.remove(temp);
                } else {
                    deleteMusic.add(id);
                }
            }
            cursor.close();
            //insert music that table lacks
            if (localMusic.size() > 0) {
                insertMusicDetail(localMusic);
            }
            if (deleteMusic.size() > 0) {
                deleteMusicDetail(deleteMusic);
            }
        }
    }

    public static void checkMusicDetailUser() {
        Cursor cursor;
        synchronized (RESOLVER) {
            cursor = RESOLVER.query(Uri.parse(URI_MUSIC + UserTableManager.getMusicDetailUserName())
                    , new String[]{DBConstants.MusicDetailUser.ID}, null, null, null);
        }
        if (cursor != null) {
            List<MusicInfo> localMusic = MusicInfo.getLocalMusic();
            List<Integer> deleteMusic = new ArrayList<Integer>();
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex(DBConstants.MusicDetailUser.ID));
                MusicInfo temp = MusicInfo.getMusicInfoById(id);
                if (temp != null) {
                    localMusic.remove(temp);
                } else {
                    deleteMusic.add(id);
                }
            }
            cursor.close();
            if (localMusic.size() > 0) {
                insertMusicDetailUser(localMusic);
            }
            if (deleteMusic.size() > 0) {
                deleteMusicDetailUser(deleteMusic);
                needUpdateMusicMenuDetail();
            }
        }
    }

    private static void needUpdateMusicMenuDetail() {
        Uri uri = Uri.parse(URI_MUSIC + UserTableManager.getMusicMenuManageName());
        synchronized (RESOLVER) {
            ContentValues values = new ContentValues();
            values.put(DBConstants.MusicMenuManage.DATA_1, "1");
            RESOLVER.update(uri, values, null, null);
        }
    }

    public static void initMusicDetailUser(String tableName) {
        Uri uri = Uri.parse(URI_MUSIC + tableName);
        List<MusicInfo> list = MusicInfo.getLocalMusic();
        for (int i = 0; i < list.size(); i++) {
            ContentValues values = new ContentValues();
            values.put(DBConstants.MusicDetailUser.ID, list.get(i).getId());
            values.put(DBConstants.MusicDetailUser.FAVORITE, 0);
            values.put(DBConstants.MusicDetailUser.LISTEN_COUNTS, 0);
            values.put(DBConstants.MusicDetailUser.AUTHORITY, 1);
            values.put(DBConstants.MusicDetailUser.DATA_1, "");
            values.put(DBConstants.MusicDetailUser.DATA_2, "");
            RESOLVER.insert(uri, values);
        }
    }

    //获取指定歌曲的专辑图片，没有则获取随机默认图片
    public static Bitmap getAlbumBitmapOrDefault(MusicInfo musicInfo) {
        Bitmap bitmap = null;
        if (musicInfo != null) {
            try {
                int id = musicInfo.getId();
                int albumId = musicInfo.getAlbumId();
                MusicFormat musicFormat = musicInfo.getMusicFormat();
                String bitmapPath = getAlbumBitmap(albumId);
                if (!musicFormat.isUnknown()) {
                    if (bitmapPath != null)
                        bitmap = BitmapFactory.decodeFile(bitmapPath);
                    if (bitmap == null)
                        bitmap = getMusicBitmap(id, albumId);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (bitmap == null) {
            bitmap = DrawUtil.getDefaultBitmap();
        }
        return bitmap;
    }

    //根据专辑的id来获取mp3文件中的专辑图片
    private static String getAlbumBitmap(int albumId) {
        String UriAlbum = "content://media/external/audio/albums";
        Cursor cursor = MusicPlayerApplication.getInstance().getContentResolver().
                query(Uri.parse(UriAlbum + "/" + Integer.toString(albumId))
                        , new String[]{"album_art"}, null, null, null);
        String album_art = null;
        if (cursor != null) {
            if (cursor.getCount() > 0 && cursor.getColumnCount() > 0) {
                cursor.moveToNext();
                album_art = cursor.getString(0);
            }
            cursor.close();
        }
        return album_art;
    }

    //根据歌曲和专辑的id来获取mp3文件中的专辑图片
    private static Bitmap getMusicBitmap(int id, int albumId) {
        Uri albumArtUri = Uri.parse("content://media/external/audio/albumart");
        Bitmap bitmap = null;
        if (id < 0 && albumId < 0)
            return null;
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            FileDescriptor fd = null;
            if (albumId < 0) {
                Uri uri = Uri.parse("content://media/external/audio/media/" + id + "/albumart");
                ParcelFileDescriptor pfd = MusicPlayerApplication.getInstance().getContentResolver().openFileDescriptor(uri, "r");
                if (pfd != null)
                    fd = pfd.getFileDescriptor();
            } else {
                Uri uri = ContentUris.withAppendedId(albumArtUri, albumId);
                ParcelFileDescriptor pfd = MusicPlayerApplication.getInstance().getContentResolver().openFileDescriptor(uri, "r");
                if (pfd != null)
                    fd = pfd.getFileDescriptor();
            }
            bitmap = BitmapFactory.decodeFileDescriptor(fd);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}